package server;

import server.container.Context;
import server.container.Engine;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Engine engine;

    public RequestProcessor(Socket socket, Engine engine) {
        this.socket = socket;
        this.engine = engine;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            HttpServlet servlet = getServlet(request.getUrl());
            if(servlet == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                servlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    private HttpServlet getServlet(String url){
        // 解析应用名和应用下的路径
        String[] split = url.substring(1).split("/", 2);
        String contextName = split[0];
        String contextPath = "/" + split[1];

        // 获取context
        Context context = engine.getHostMap().get("localhost").getContextMap().get(contextName);

        // 获取相应的路径
        HttpServlet httpServlet = context.getServletMap().get(contextPath);
        return httpServlet;
    }
}
